// 表单验证逻辑
document.getElementById('goodsForm').addEventListener('submit', function(e) {
    let isValid = true;

    // 验证商品名称
    const goodsName = document.getElementById('goodsName');
    if(!goodsName.value.trim()) {
        showError('nameError', '商品名称不能为空');
        isValid = false;
    }

    // 验证图片
    const fileInput = document.getElementById('goodsImg');
    if(fileInput.files.length === 0) {
        showError('fileError', '请至少上传一张商品图片');
        isValid = false;
    }

    // 验证价格
    const price = parseFloat(document.getElementById('goodsPrice').value);
    const specialPrice = parseFloat(document.getElementById('goodsSpecialPrice').value || 0);

    if(isNaN(price) || price <= 0) {
        showError('priceError', '请输入有效的商品价格');
        isValid = false;
    }

    if(specialPrice > 0 && specialPrice >= price) {
        showError('specialPriceError', '特惠价必须低于原价');
        isValid = false;
    }

    // 验证库存
    const stock = parseInt(document.getElementById('goodsStock').value);
    if(isNaN(stock) || stock < 0) {
        showError('stockError', '库存数量不能为负数');
        isValid = false;
    }

    if(!isValid) {
        e.preventDefault(); // 阻止表单提交
    }
});

// 文件上传交互
const fileInput = document.getElementById('goodsImg');
const fileLabel = document.getElementById('fileLabel');
const fileNames = document.getElementById('fileNames');

fileInput.addEventListener('change', function() {
    if(this.files.length > 0) {
        hideError('fileError');
        let names = '';
        for(let i = 0; i < this.files.length; i++) {
            names += `<div>${this.files[i].name}</div>`;
        }
        fileNames.innerHTML = names;
        fileLabel.querySelector('span').textContent = `已选择 ${this.files.length} 个文件`;
    }
});

// 拖拽上传功能
fileLabel.addEventListener('dragover', function(e) {
    e.preventDefault();
    this.style.borderColor = '#4285f4';
    this.style.backgroundColor = '#e8f0fe';
});

fileLabel.addEventListener('dragleave', function() {
    this.style.borderColor = '#ddd';
    this.style.backgroundColor = '#f8f9fa';
});

fileLabel.addEventListener('drop', function(e) {
    e.preventDefault();
    this.style.borderColor = '#ddd';
    this.style.backgroundColor = '#f8f9fa';

    if(e.dataTransfer.files.length > 0) {
        fileInput.files = e.dataTransfer.files;
        const event = new Event('change');
        fileInput.dispatchEvent(event);
    }
});

// 辅助函数
function showError(elementId, message) {
    const el = document.getElementById(elementId);
    el.textContent = message;
    el.style.display = 'block';
}

function hideError(elementId) {
    const el = document.getElementById(elementId);
    el.style.display = 'none';
}